<template>
  <view class="appointment-page">
    <!-- Tab栏 -->
    <view class="tab-bar">
      <view v-for="(tab, index) in tabs" :key="index" class="tab-item" :class="{ active: currentTab === index }" @tap="handleTabChange(index)">
        <text>{{ tab }}</text>
      </view>
    </view>

    <!-- 内容区域 -->
    <swiper class="swiper-content" :current="currentTab" @change="handleSwiperChange">
      <!-- 待使用 -->
      <swiper-item>
        <scroll-view scroll-y class="scroll-view">
          <view class="appointment-list">
            <view
              class="appointment-card"
              v-for="item in appointmentList.filter((item:any) => item.status === '10')"
              :key="item.id"
              @tap="handleToDetail(item)"
            >
              <view class="shop-info">
                <text class="shop-name">{{ item.shopInfo.shopName }}</text>
                <text class="appointment-time">{{ item.applyTime }}</text>
              </view>
              <view class="action-btn">
                <button class="cancel-btn" @tap.stop="handleCancel(item)">取消</button>
              </view>
            </view>
          </view>
        </scroll-view>
      </swiper-item>

      <!-- 已完成 -->
      <swiper-item>
        <scroll-view scroll-y class="scroll-view">
          <view class="appointment-list">
            <view
              class="appointment-card"
              v-for="item in appointmentList.filter((item:any) => item.status === '13')"
              :key="item.id"
              @tap="handleToDetail(item)"
            >
              <view class="shop-info">
                <text class="shop-name">{{ item.shopInfo.shopName }}</text>
                <text class="appointment-time">{{ item.applyTime }}</text>
              </view>
              <view class="status-text">已完成</view>
            </view>
          </view>
        </scroll-view>
      </swiper-item>
    </swiper>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { getMyAppointment } from '@/api/store';
import { onShow } from '@dcloudio/uni-app';
import { useUserStore } from '@/stores/user';
import request from '@/utils/request'

const userStore = useUserStore();

const tabs = ['待到店', '已完成'];
const currentTab = ref(0);

const appointmentList = ref([]);

const fetchAppointmentList = async () => {
  try {
    const res = await getMyAppointment();
    if (res.code === 200 && res.rows) {
      appointmentList.value = res.rows;
    }
  } catch (error) {
    console.error('获取预约列表失败:', error);
    uni.showToast({
      title: '获取预约列表失败',
      icon: 'none',
    });
  }
};

const handleTabChange = (index: number) => {
  currentTab.value = index;
};

const handleSwiperChange = (e: any) => {
  currentTab.value = e.detail.current;
};

// 跳转到预约详情
const handleToDetail = (item: any) => {
  const params = {
    id: item.id,
    shopName: item.shopInfo.shopName,
    storeHours: item.shopInfo.storeHours,
    userName: userStore.userInfo.user.nickName || '游客',
    itemProjectName: item.shopItem.itemName,
    guideName: item.consultant.nickName,
    from: 'myAppointment', // 添加来源标识
  };

  // 将对象转换为查询字符串
  const queryString = Object.keys(params)
    .map((key) => `${key}=${encodeURIComponent(params[key])}`)
    .join('&');

  uni.navigateTo({
    url: `/pages/appointment/detail?${queryString}`,
  });
};

// 取消预约
const handleCancel = (item: any) => {
  uni.showModal({
    title: '提示',
    content: '确定要取消预约吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          const res = await request({
            url: '/basics/itemApply',
            method: 'PUT',
            data: {
              id: item.id,
              status: '12'
            }
          });
          
          if (res.code === 200) {
            uni.showToast({
              title: '取消预约成功',
              icon: 'success'
            });
            // 刷新列表
            fetchAppointmentList();
          } else {
            uni.showToast({
              title: res.message || '取消失败',
              icon: 'none'
            });
          }
        } catch (error) {
          console.error('取消预约失败:', error);
          uni.showToast({
            title: '取消预约失败',
            icon: 'none'
          });
        }
      }
    }
  });
};

onShow(() => {
  fetchAppointmentList();
});
</script>

<style lang="scss" scoped>
.appointment-page {
  min-height: 100vh;
  background: #f3f3fd;
}

.tab-bar {
  display: flex;
  background: #fff;
  padding: 0 30rpx;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1;

  .tab-item {
    flex: 1;
    display: flex;
    justify-content: center;
    padding: 30rpx 0;
    position: relative;

    text {
      font-size: 28rpx;
      color: #666;
    }

    &.active {
      text {
        color: #4e6ef2;
        font-weight: 500;
      }

      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 40rpx;
        height: 4rpx;
        background: #4e6ef2;
        border-radius: 2rpx;
      }
    }
  }
}

.swiper-content {
  height: calc(100vh - 90rpx);
  margin-top: 90rpx;
}

.scroll-view {
  height: 100%;
}

.appointment-list {
  padding: 20rpx;
}

.appointment-card {
  background: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .shop-info {
    .shop-name {
      font-size: 28rpx;
      color: #333;
      display: block;
      margin-bottom: 8rpx;
    }

    .appointment-time {
      font-size: 26rpx;
      color: #999;
    }
  }

  .action-btn {
    .cancel-btn {
      color: #666;
      background: #f5f5f5;
      border-radius: 24rpx;
      padding: 8rpx 24rpx;
      border: none;
      padding: 0;
      display: flex;
      justify-content: center;
      align-items: center;
      width: 125rpx;
      height: 43rpx;
      background: linear-gradient(138deg, #ed483b, #f88a81);
      box-shadow: 0rpx 6rpx 50rpx 1rpx rgba(237, 72, 59, 0.44);
      border-radius: 22rpx;
      font-size: 26rpx;
      color: #ffffff;
      &:after {
        display: none;
      }
    }
  }

  .status-text {
    font-size: 26rpx;
    color: #999;
  }

  .status-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 20rpx;

    .status {
      font-size: 26rpx;
      color: #999;
    }

    .cancel-btn {
      font-size: 26rpx;
      color: #666;
    }
  }
}
</style>
